/**
 * 纪念日编辑器 - 处理纪念日的添加和删除功能
 */
class MemoryEditor {
  constructor() {
    this.uploadManager = new UploadManager();
    this.initUI();
    this.setupEventListeners();
  }

  /**
   * 初始化UI元素
   */
  initUI() {
    // 在页面中添加编辑控件
    const memoryContainer = document.querySelector('.memory-timeline');
    if (!memoryContainer) return;

    // 添加新纪念日按钮
    const addButtonContainer = document.createElement('div');
    addButtonContainer.className = 'add-memory-btn-container text-center my-4';
    addButtonContainer.innerHTML = `
      <button id="addMemoryBtn" class="btn btn-primary">
        <i class="fas fa-plus"></i> 添加新纪念日
      </button>
    `;
    memoryContainer.parentNode.insertBefore(addButtonContainer, memoryContainer);

    // 添加纪念日表单模态框
    const modalHTML = `
      <div class="modal fade" id="memoryFormModal" tabindex="-1" aria-labelledby="memoryFormModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="memoryFormModalLabel">添加新纪念日</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              <form id="memoryForm">
                <div class="mb-3">
                  <label for="memoryTitle" class="form-label">标题</label>
                  <input type="text" class="form-control" id="memoryTitle" required>
                </div>
                <div class="mb-3">
                  <label for="memoryDate" class="form-label">日期</label>
                  <input type="date" class="form-control" id="memoryDate" required>
                </div>
                <div class="mb-3">
                  <label for="memoryType" class="form-label">类型</label>
                  <select class="form-select" id="memoryType" required>
                    <option value="">选择类型...</option>
                    <option value="anniversary">纪念日</option>
                    <option value="festival">节日</option>
                    <option value="birthday">生日</option>
                    <option value="special">特别的日子</option>
                  </select>
                </div>
                <div class="mb-3 form-check">
                  <input type="checkbox" class="form-check-input" id="memoryIsSpecial">
                  <label class="form-check-label" for="memoryIsSpecial">标记为重要</label>
                </div>
                <div class="mb-3">
                  <label for="memoryDescription" class="form-label">描述</label>
                  <textarea class="form-control" id="memoryDescription" rows="4"></textarea>
                </div>
                <div class="mb-3">
                  <label for="memoryTags" class="form-label">标签</label>
                  <input type="text" class="form-control" id="memoryTags" placeholder="用逗号分隔多个标签">
                  <small class="form-text text-muted">例如：重要的日子,爱的开始</small>
                </div>
                <div class="mb-3">
                  <label class="form-label">照片</label>
                  <div class="d-flex align-items-center">
                    <input type="file" class="form-control me-2" id="memoryPhotos" accept="image/*" multiple>
                    <button type="button" class="btn btn-outline-primary" id="addMemoryPhotosBtn">
                      <i class="fas fa-plus"></i>
                    </button>
                  </div>
                  <div class="row mt-2" id="memoryPhotosPreview"></div>
                </div>
                <div id="memory-photos-container">
                  <!-- 这里将动态添加照片相关字段 -->
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" id="saveMemoryBtn">保存纪念日</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 删除确认模态框 -->
      <div class="modal fade" id="deleteMemoryConfirmModal" tabindex="-1" aria-labelledby="deleteMemoryConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="deleteMemoryConfirmModalLabel">确认删除</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              确定要删除这个纪念日吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-danger" id="confirmDeleteMemoryBtn">删除</button>
            </div>
          </div>
        </div>
      </div>
    `;

    // 将模态框添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);

    // 为每个纪念日添加编辑和删除按钮
    this.addMemoryControls();
  }

  /**
   * 为纪念日添加编辑和删除控件
   */
  addMemoryControls() {
    // 为过去的纪念日添加删除按钮
    const memoryItems = document.querySelectorAll('.memory-item');
    
    memoryItems.forEach(item => {
      // 获取纪念日ID
      const memoryId = item.dataset.id;
      if (!memoryId) return;
      
      // 添加控制按钮
      const controlsContainer = document.createElement('div');
      controlsContainer.className = 'memory-controls position-absolute top-0 end-0 m-2';
      controlsContainer.innerHTML = `
        <button class="btn btn-sm btn-danger delete-memory-btn" data-id="${memoryId}">
          <i class="fas fa-trash"></i>
        </button>
      `;
      
      item.style.position = 'relative';
      item.appendChild(controlsContainer);
    });
    
    // 为即将到来的事件添加删除按钮
    const upcomingItems = document.querySelectorAll('.upcoming-event-item');
    
    upcomingItems.forEach(item => {
      // 获取事件ID
      const eventId = item.dataset.id;
      if (!eventId) return;
      
      // 添加控制按钮
      const controlsContainer = document.createElement('div');
      controlsContainer.className = 'memory-controls position-absolute top-0 end-0 m-2';
      controlsContainer.innerHTML = `
        <button class="btn btn-sm btn-danger delete-memory-btn" data-id="${eventId}">
          <i class="fas fa-trash"></i>
        </button>
      `;
      
      item.style.position = 'relative';
      item.appendChild(controlsContainer);
    });
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // 添加纪念日按钮点击事件
    const addMemoryBtn = document.getElementById('addMemoryBtn');
    if (addMemoryBtn) {
      addMemoryBtn.addEventListener('click', () => {
        // 重置表单
        document.getElementById('memoryForm').reset();
        document.getElementById('memoryPhotosPreview').innerHTML = '';
        document.getElementById('memory-photos-container').innerHTML = '';
        
        // 设置默认日期为今天
        document.getElementById('memoryDate').valueAsDate = new Date();
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('memoryFormModal'));
        modal.show();
      });
    }

    // 上传纪念日照片预览
    const memoryPhotos = document.getElementById('memoryPhotos');
    const addMemoryPhotosBtn = document.getElementById('addMemoryPhotosBtn');
    if (memoryPhotos && addMemoryPhotosBtn) {
      addMemoryPhotosBtn.addEventListener('click', () => {
        const files = memoryPhotos.files;
        if (files.length === 0) return;
        
        // 添加照片预览和描述输入框
        this.addMemoryPhotoInputs(files);
        
        // 清空文件输入框，以便再次选择文件
        memoryPhotos.value = '';
      });
    }

    // 保存纪念日按钮点击事件
    const saveMemoryBtn = document.getElementById('saveMemoryBtn');
    if (saveMemoryBtn) {
      saveMemoryBtn.addEventListener('click', () => {
        this.saveMemory();
      });
    }

    // 设置删除纪念日按钮的事件委托
    document.addEventListener('click', (event) => {
      if (event.target.closest('.delete-memory-btn')) {
        const btn = event.target.closest('.delete-memory-btn');
        const memoryId = btn.dataset.id;
        
        // 设置当前要删除的纪念日ID
        document.getElementById('confirmDeleteMemoryBtn').dataset.id = memoryId;
        
        // 显示确认删除模态框
        const modal = new bootstrap.Modal(document.getElementById('deleteMemoryConfirmModal'));
        modal.show();
      }
    });

    // 确认删除按钮点击事件
    const confirmDeleteMemoryBtn = document.getElementById('confirmDeleteMemoryBtn');
    if (confirmDeleteMemoryBtn) {
      confirmDeleteMemoryBtn.addEventListener('click', () => {
        const memoryId = confirmDeleteMemoryBtn.dataset.id;
        this.deleteMemory(memoryId);
      });
    }
  }

  /**
   * 添加纪念日照片输入框
   * @param {FileList} files - 选择的照片文件
   */
  addMemoryPhotoInputs(files) {
    const container = document.getElementById('memory-photos-container');
    const photosPreview = document.getElementById('memoryPhotosPreview');
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const photoId = Date.now() + i;
      
      // 添加预览
      const previewCol = document.createElement('div');
      previewCol.className = 'col-md-3 mb-3';
      previewCol.dataset.photoId = photoId;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        previewCol.innerHTML = `
          <div class="position-relative">
            <img src="${e.target.result}" class="img-thumbnail w-100" alt="照片预览">
            <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-memory-photo" data-photo-id="${photoId}">
              <i class="fas fa-times"></i>
            </button>
          </div>
        `;
      };
      reader.readAsDataURL(file);
      
      photosPreview.appendChild(previewCol);
      
      // 添加照片表单字段
      const photoFieldset = document.createElement('fieldset');
      photoFieldset.className = 'mb-3 memory-photo-fieldset';
      photoFieldset.dataset.photoId = photoId;
      photoFieldset.innerHTML = `
        <input type="hidden" name="memoryPhotoFile_${photoId}" value="${file.name}" class="memory-photo-file">
        <div class="mb-3">
          <label class="form-label">照片描述</label>
          <input type="text" class="form-control memory-photo-description" required>
        </div>
      `;
      
      container.appendChild(photoFieldset);
      
      // 添加删除照片的事件监听
      setTimeout(() => {
        const removeBtn = document.querySelector(`.remove-memory-photo[data-photo-id="${photoId}"]`);
        if (removeBtn) {
          removeBtn.addEventListener('click', () => {
            // 删除预览和表单字段
            const preview = document.querySelector(`.col-md-3[data-photo-id="${photoId}"]`);
            const fieldset = document.querySelector(`.memory-photo-fieldset[data-photo-id="${photoId}"]`);
            
            if (preview) preview.remove();
            if (fieldset) fieldset.remove();
          });
        }
      }, 100);
    }
  }

  /**
   * 保存纪念日
   */
  async saveMemory() {
    try {
      const titleInput = document.getElementById('memoryTitle');
      const dateInput = document.getElementById('memoryDate');
      const typeInput = document.getElementById('memoryType');
      const isSpecialInput = document.getElementById('memoryIsSpecial');
      const descriptionInput = document.getElementById('memoryDescription');
      const tagsInput = document.getElementById('memoryTags');
      
      // 表单验证
      if (!titleInput.value || !dateInput.value || !typeInput.value) {
        alert('请填写所有必填字段');
        return;
      }
      
      // 显示加载状态
      const saveBtn = document.getElementById('saveMemoryBtn');
      const originalText = saveBtn.innerHTML;
      saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
      saveBtn.disabled = true;
      
      // 1. 上传照片
      const photoFieldsets = document.querySelectorAll('.memory-photo-fieldset');
      const photos = [];
      
      for (const fieldset of photoFieldsets) {
        const photoId = fieldset.dataset.photoId;
        const descriptionInput = fieldset.querySelector('.memory-photo-description');
        
        if (!descriptionInput.value) {
          alert('请填写所有照片的描述');
          saveBtn.innerHTML = originalText;
          saveBtn.disabled = false;
          return;
        }
        
        // 获取对应的文件
        const previewEl = document.querySelector(`.col-md-3[data-photo-id="${photoId}"]`);
        if (previewEl) {
          const imgSrc = previewEl.querySelector('img').src;
          
          // 如果是base64格式，表示是新上传的文件
          if (imgSrc.startsWith('data:image')) {
            // 查找对应的文件
            const fileName = fieldset.querySelector('.memory-photo-file').value;
            let photoFile = null;
            
            // 从原始文件输入中查找匹配的文件
            const fileInput = document.getElementById('memoryPhotos');
            for (let i = 0; i < fileInput.files.length; i++) {
              if (fileInput.files[i].name === fileName) {
                photoFile = fileInput.files[i];
                break;
              }
            }
            
            if (photoFile) {
              // 上传照片
              const photoUploadResult = await this.uploadManager.uploadImage(photoFile, 'memory');
              
              photos.push({
                src: photoUploadResult.filePath,
                description: descriptionInput.value
              });
            }
          }
        }
      }
      
      // 处理标签
      const tags = tagsInput.value
        .split(',')
        .map(tag => tag.trim())
        .filter(tag => tag !== '');
      
      // 2. 构建纪念日数据
      const memoryData = {
        title: titleInput.value,
        date: dateInput.value,
        type: typeInput.value,
        isSpecial: isSpecialInput.checked,
        description: descriptionInput.value,
        photos: photos,
        tags: tags
      };
      
      // 3. 保存纪念日数据
      const result = await this.uploadManager.addMemory(memoryData);
      
      // 4. 处理结果
      if (result.success) {
        alert('纪念日添加成功');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('memoryFormModal'));
        modal.hide();
        
        // 刷新页面以显示新纪念日
        window.location.reload();
      } else {
        throw new Error(result.message || '添加纪念日失败');
      }
    } catch (error) {
      console.error('保存纪念日出错:', error);
      alert(`添加纪念日失败: ${error.message}`);
      
      // 恢复按钮状态
      const saveBtn = document.getElementById('saveMemoryBtn');
      saveBtn.innerHTML = '<i class="fas fa-save"></i> 保存纪念日';
      saveBtn.disabled = false;
    }
  }

  /**
   * 删除纪念日
   * @param {string} memoryId - 要删除的纪念日ID
   */
  async deleteMemory(memoryId) {
    try {
      // 显示加载状态
      const confirmBtn = document.getElementById('confirmDeleteMemoryBtn');
      const originalText = confirmBtn.innerHTML;
      confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 删除中...';
      confirmBtn.disabled = true;
      
      // 调用删除API
      const result = await this.uploadManager.deleteMemory(memoryId);
      
      // 处理结果
      if (result.success) {
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('deleteMemoryConfirmModal'));
        modal.hide();
        
        // 从页面中移除纪念日
        const memoryItem = document.querySelector(`.memory-item[data-id="${memoryId}"]`);
        if (memoryItem) {
          memoryItem.remove();
        } else {
          // 检查是否是即将到来的事件
          const upcomingItem = document.querySelector(`.upcoming-event-item[data-id="${memoryId}"]`);
          if (upcomingItem) {
            upcomingItem.remove();
          } else {
            // 如果找不到对应元素，刷新页面
            window.location.reload();
          }
        }
        
        alert('纪念日已成功删除');
      } else {
        throw new Error(result.message || '删除纪念日失败');
      }
    } catch (error) {
      console.error('删除纪念日出错:', error);
      alert(`删除纪念日失败: ${error.message}`);
      
      // 恢复按钮状态
      const confirmBtn = document.getElementById('confirmDeleteMemoryBtn');
      confirmBtn.innerHTML = originalText;
      confirmBtn.disabled = false;
    }
  }
}

// 当文档加载完成时初始化编辑器
document.addEventListener('DOMContentLoaded', () => {
  // 检查是否在纪念日页面
  if (document.querySelector('.memory-timeline')) {
    new MemoryEditor();
  }
}); 